<template>
  <div style="position: relative">
    <img
      v-if="data.list.length == 0"
      class="form-empty"
      src="~@/assets/bgForm.jpg"
    />

    <a-form
      layout="horizontal"
      :labelAlign="data.config.labelPosition"
      :labelCol="{ style: `width: ${data.config.labelWidth}px;float:left` }"
      :wrapperCol="{ style: `width: ${data.config.size}%;float:left` }"
    >
      <draggable
        class="height"
        v-model="data.list"
        v-bind="{
          animation: 200,
          group: 'people',
        }"
        @end="handleMoveEnd"
        @add="handleWidgetAdd"
        item-key="key"
      >
        <template #item="{ element, index }">
          <div class="widget-view">
            <template v-if="element.type == 'grid'">
              <a-row
                :class="{ active: selectWidget.key == element.key }"
                v-if="element && element.key"
                :key="index"
                :gutter="element.options.gutter ? element.options.gutter : 0"
                @click.enter="handleSelectWidget(index)"
                @dblclick.enter.stop="openSetting()"
              >
                <a-col
                  v-for="(col, colIndex) in element.columns"
                  :key="colIndex"
                  :offset="col.offset"
                  :span="col.span ? col.span : 0"
                >
                  <draggable
                    class="widget-col-list"
                    :class="{
                      borderHighlight: selectWidget.key == element.key,
                    }"
                    v-model="col.list"
                    :no-transition-on-drag="true"
                    v-bind="{
                      group: 'people',
                      animation: 200,
                    }"
                    item-key="key"
                    @end="handleMoveEnd"
                    @add="handleWidgetColAdd($event, element, colIndex)"
                  >
                    <template #item="{ element, index }">
                      <div>
                        <widget-form-item
                          v-if="element.type !== 'grid'"
                          :element="element"
                          :key="element.key"
                          v-model:select="selectWidget"
                          :index="index"
                          :widgetForm="col"
                          @openSetting="openSetting"
                        ></widget-form-item>
                      </div>
                    </template>
                  </draggable>
                </a-col>
                <div
                  class="widget-view-drag"
                  v-if="selectWidget.key == element.key"
                >
                  <DragOutlined />
                </div>
                <div
                  class="widget-view-action"
                  v-if="selectWidget.key == element.key"
                >
                  <span @click.stop="handleWidgetDelete(index)">
                    <DeleteOutlined />
                  </span>
                </div>
              </a-row>
            </template>
            <template v-else>
              <widget-form-item
                v-if="element && element.key"
                :key="element.key"
                :element="element"
                v-model:select="selectWidget"
                :index="index"
                :widgetForm="data"
                @openSetting="openSetting"
              ></widget-form-item>
            </template>
          </div>
        </template>
      </draggable>
    </a-form>
  </div>
</template>

<script>
  import Draggable from 'vuedraggable'
  import WidgetFormItem from './WidgetFormItem'
  import { getGuid } from '@/utils/util'
  import { DeleteOutlined, DragOutlined } from '@ant-design/icons-vue'
  export default {
    components: {
      Draggable,
      WidgetFormItem,
      DeleteOutlined,
      DragOutlined,
    },
    // eslint-disable-next-line vue/require-prop-types
    props: ['widgetForm'],
    data() {
      return {
        data: this.widgetForm,
        selectWidget: {},
        tableform: {},
      }
    },
    created() {
      if (this.data.list.length > 0) {
        this.selectWidget = this.data.list[0]
      }
    },
    mounted() {
      document.body.ondrop = function (event) {
        const isFirefox =
          navigator.userAgent.toLowerCase().indexOf('firefox') > -1
        if (isFirefox) {
          event.preventDefault()
          event.stopPropagation()
        }
      }
    },
    methods: {
      openSetting() {
        this.$emit('openSetting', true)
      },

      handleMoveEnd({ newIndex, oldIndex }) {
        console.log('index', newIndex, oldIndex)
      },
      handleSelectWidget(index) {
        console.log(index, '#####')
        this.selectWidget = this.data.list[index]
      },
      handleWidgetAdd(evt) {
        // console.log('add', evt)
        const newIndex = evt.newIndex
        //为拖拽到容器的元素添加唯一 key
        // const key = Date.parse(new Date()) + '-' + Math.ceil(Math.random() * 99999)
        const key = getGuid()

        let addData = {
          ...this.data.list[newIndex],
          options: {
            ...this.data.list[newIndex].options,
          },
          key,
        }

        if (addData.type === 'grid') {
          addData = {
            ...addData,
            columns: addData.columns.map((item) => ({
              ...item,
            })),
          }
        }
        this.data.list[newIndex] = addData
        // this.$set(this.data.list, newIndex, {
        //   ...this.data.list[newIndex],
        //   options: {
        //     ...this.data.list[newIndex].options,
        //     remoteFunc: undefined,
        //   },
        //   key,
        //   // 绑定键值
        // })
        // this.data.list[newIndex].key = key

        this.selectWidget = this.data.list[newIndex]
      },

      handleWidgetColAdd($event, row, colIndex) {
        console.log('coladd', $event, row, colIndex)
        const newIndex = $event.newIndex
        const oldIndex = $event.oldIndex
        const item = $event.item

        // 防止布局元素的嵌套拖拽
        if (item.className.indexOf('data-grid') >= 0) {
          // 如果是列表中拖拽的元素需要还原到原来位置
          item.tagName === 'DIV' &&
            this.data.list.splice(
              oldIndex,
              0,
              row.columns[colIndex].list[newIndex]
            )

          row.columns[colIndex].list.splice(newIndex, 1)

          return false
        }

        // const key = Date.parse(new Date()) + '-' + Math.ceil(Math.random() * 99999)
        const key = getGuid()
        let addData = {
          ...row.columns[colIndex].list[newIndex],
          options: {
            ...row.columns[colIndex].list[newIndex].options,
          },
          key,
        }

        row.columns[colIndex].list[newIndex] = addData

        this.selectWidget = row.columns[colIndex].list[newIndex]
      },
      handleWidgetDelete(index) {
        if (this.data.list.length - 1 === index) {
          if (index === 0) {
            this.selectWidget = {}
          } else {
            this.selectWidget = this.data.list[index - 1]
          }
        } else {
          this.selectWidget = this.data.list[index + 1]
        }

        this.$nextTick(() => {
          this.data.list.splice(index, 1)
        })
      },
    },
    watch: {
      select(val) {
        this.selectWidget = val
      },
      selectWidget: {
        handler(val) {
          // console.log(val)
          this.$emit('changeSelect', val)
        },
        deep: true,
      },
    },
  }
</script>
<style lang="less">
  .height {
    height: calc(100vh - 300px);
  }
  .widget-view {
    position: relative;
    border: 1px dashed rgba(170, 170, 170, 0.7);
    background-color: rgba(255, 255, 255, 0.3);
  }

  .widget-view-action {
    position: absolute;
    right: 0;
    bottom: 0px;
    height: 20px;
    line-height: 19px;
    z-index: 9;
    cursor: pointer;

    //top: 100%;
    z-index: 1;
    background: none !important;
    span {
      position: absolute;
      span {
        border-color: #ff5b57;
        color: #ff5b57;
        background: #fff;
        width: 22px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        border-radius: 50%;
        font-size: 12px;
        border: 1px solid;
        cursor: pointer;
        &:hover {
          color: #fff;
          background: #ff5b57;
          border-color: #ff5b57;
        }
      }
      &:nth-child(1) {
        right: 3px;
      }
      &:nth-child(2) {
        span {
          border-color: #348fe2 !important;
          color: #348fe2 !important;
          &:hover {
            color: #fff !important;
            background: #348fe2;
            border-color: #348fe2;
          }
        }
        right: 28px;
      }
    }
  }

  .widget-view-drag {
    position: absolute;
    top: 0px;
    z-index: 99;
    width: 22px;
    height: 22px;
    line-height: 20px;
    text-align: center;
    border-radius: 50%;
    font-size: 13px;
    border: 1px solid;
    color: #fff !important;
    background: #348fe2;
    border-color: #348fe2;
    .anticon {
      margin-right: 0.5px !important;
    }
  }

  /* 栅格布局 */
  .widget-col-list {
    min-height: 40px;
    border: 1px dashed #ccc;
    background: rgb(253, 253, 253);
    margin-bottom: 10px;
  }

  // 鼠标选中样式
  .active {
    background-color: rgba(241, 243, 244, 0.8) !important;
  }
  // a-row 鼠标选中样式
  .borderHighlight {
    border: 1px dashed #409eff;
  }
  .form-empty {
    position: absolute;
    text-align: center;
    width: 600px;
    font-size: 20px;
    top: 10%;
    left: 30%;
    margin-left: -150px;
    color: #ccc;
  }
</style>
